<?php
namespace Home\Controller;
use Think\Controller;
class RechargeController extends Controller
{

    public function index()
    {
        $order = D('order');
        $member = M('member');
        $money = I('money');
        $uid = I('uid');
        $status = I('status');

        if(!$money) returnApiError(1,'请填写金额');
        if(!$uid) returnApiError(1,'请填写uid');
        if(!$status) returnApiError(1,'请填写stauts参数');
        $paysn = $order->makePaySn($uid);
        $ordersn = $order->orderSn();
        $data = $member->find($uid);
        if(!$data){
            returnApiError(1,'会员不存在');
        }
       /* $recharge = M('pd_recharge');
        $r_data = $recharge->where("pdr_member_id = $uid")->field('pdr_id,pdr_add_time')->order(array('pdr_id'=>'desc'))->find();
        if($r_data['pdr_add_time']+10 >= time()){
            sleep(2);
        }*/
        $member_name = $data['member_name'];
        $member_amount = $data['available_predeposit'];
        $this->create($uid,$paysn,$money,$member_name,$ordersn,$member_amount);
        if($status ==  1){
            $this->wxpay($paysn,$money);
        }

        if($status ==  2){
            $this->alipay($paysn,$money);
        }

        if($status ==  3){
            $this->iosalipay($paysn,$money);
        }

    }

    /**
     * 创建充值订单
     */
    public function create($uid,$paysn,$money,$member_name,$ordersn,$member_amount){
        $recharge = M('pd_recharge');
        $data = array();
        $data['pdr_member_id'] = $uid;
        $data['pdr_member_name'] = $member_name;
        $data['pdr_sn'] = $ordersn;
        $data['pdr_amount'] = $money;
        $data['pdr_member_amount'] = $member_amount;
        $data['pdr_trade_sn'] = $paysn;
        $data['pdr_add_time'] = time();
        $data['pdr_payment_state'] = 0;

        $add = $recharge->add($data);
        if(!$add){
            returnApiError(1,'创建充值订单失败');
        }
    }

    /**
     * @param $uid
     * @param $paysn
     * 微信支付
     */
    public function wxpay($paysn,$money){

        Vendor('Wxpay.api');

        $config = new \WxPayConfig();
        $api = new \WxPayApi();
        $unified = new \WxPayUnifiedOrder();

        $this->appid =  $config::APPID;
        $this->key =  $config::KEY;
        $this->mchid =  $config::MCHID;
        $this->appsecret =  $config::KEY;

        $trade_no = $paysn;

        if(!$trade_no) returnApiError(1,'缺少订单pay_sn参数');
        $unified->SetOut_trade_no($trade_no); //订单号
        $unified->SetBody('充值');            //商品详情
        $unified->SetTotal_fee($money*100);      //总金额
        //$unified->SetProduct_id('1111');    //商品id
        $unified->SetTrade_type('APP');
        $unified->SetNotify_url(SHOP_SITE_URL.'/api/index.php/Home/Recharge/wxnotify.html');

        $result = $api->unifiedOrder($unified);
        ob_clean() ;
        if($result['return_code'] == 'SUCCESS'){
            //二次签名
            $string = "appid=".$this->appid."&noncestr=".$result['nonce_str']."&package=Sign=WXPay&partnerid=".$this->mchid."&prepayid=".$result['prepay_id']."&timestamp=".time()."&key=".$this->key;
            $sign = strtolower(md5($string));
            $data = array(
                'appid' => $this->appid,
                'mch_id' => $this->mchid,
                'sign' =>  $sign,
                'nonce_str' => $result['nonce_str'],
                'prepay_id' => $result['prepay_id'],
                'times' => time(),                   //10位
            );

            returnApiSuccess('ok',$data);
        }else{
            returnApiError(1,$result['return_msg']);
        }
    }

    /**
     * 支付宝支付
     */
    public function alipay($paysn,$money){
        require_once("./ThinkPHP/Library/Vendor/alipay/alipay.config.php");
        Vendor('alipay/alipayapi');

        $param = array(
            'partner' => '"2088811907938392"',
            'seller_id' => '"pengrun@un-eagle.com"',
            'out_trade_no' => '"'.$paysn.'"',
            'subject' => '"充值"',
            'body' => '"充值"',
            'total_fee' => '"'.$money.'"',    //总金额
            'notify_url' => '"'.SHOP_SITE_URL.'/api/index.php/Home/Recharge/alinotify.html"',
            'service' => '"mobile.securitypay.pay"',
            'payment_type' => '"1"',
            '_input_charset' => '"utf-8"',
            'it_b_pay' => '"30m"',
            'return_url' => '"'.SHOP_SITE_URL.'/api/index.php/Home/Alipay/alireturn_url.html"',
        );

        //$param = argSort(paraFilter($param));
        $prestr = createLinkstring($param);
        $sign = rsaSign($prestr,'./ThinkPHP/Library/Vendor/alipay/key/rsa_private_key.pem');

        $json_param = array(
            'partner' => '2088811907938392',
            'seller_id' => 'pengrun@un-eagle.com',
            'out_trade_no' => $paysn,
            'subject' => '充值',
            'body' => '充值',
            'total_fee' => $money,    //总金额
            'notify_url' => SHOP_SITE_URL.'/api/index.php/Home/Recharge/alinotify.html',
            'service' => 'mobile.securitypay.pay',
            'payment_type' => '1',
            '_input_charset' => 'utf-8',
            'it_b_pay' => '30m',
            'return_url' => SHOP_SITE_URL.'/api/index.php/Home/Alipay/alireturn_url.html',
            //'string' => $prestr,
        );


        $json_param['sign'] = $sign;
        $json_param['sign_type'] = 'RSA';

        returnApiSuccess('ok',$json_param);
    }

    /**
     * ios支付宝支付
     */
    public function iosalipay($paysn,$money){
        require_once("./ThinkPHP/Library/Vendor/alipay/alipay.config.php");
        Vendor('alipay/alipayapi');

        $param = array(
            'partner' => '"2088811907938392"',
            'seller_id' => '"pengrun@un-eagle.com"',
            'out_trade_no' => '"'.$paysn.'"',
            'subject' => '"充值"',
            'body' => '"充值"',
            'total_fee' => '"'.$money.'"',    //总金额
            'notify_url' => '"'.SHOP_SITE_URL.'/api/index.php/Home/Recharge/alinotify.html"',
            'service' => '"mobile.securitypay.pay"',
            'payment_type' => '"1"',
            '_input_charset' => '"utf-8"',
            'it_b_pay' => '"30m"',

        );

        //$param = argSort(paraFilter($param));
        $prestr = createLinkstring($param);
        $sign = rsaSign($prestr,'./ThinkPHP/Library/Vendor/alipay/key/rsa_private_key.pem');

        $json_param = array(
            'partner' => '2088811907938392',
            'seller_id' => 'pengrun@un-eagle.com',
            'out_trade_no' => $paysn,
            'subject' => '充值',
            'body' => '充值',
            'total_fee' => $money,    //总金额
            'notify_url' => SHOP_SITE_URL.'/api/index.php/Home/Recharge/alinotify.html',
            'service' => 'mobile.securitypay.pay',
            'payment_type' => '1',
            '_input_charset' => 'utf-8',
            'it_b_pay' => '30m',

        );


        $json_param['sign'] = $sign;
        $json_param['sign_type'] = 'RSA';
        $json_param['private_key'] = 'MIICXAIBAAKBgQDK/TWLUGKeNpcm4cY+uNw6Z8O1vFL8C2LJE+9Fw8AfUFP/BMc9dMkr0+6elfSztk36nbyOHmTCyTFM1+8ekpQfaz25hTq5lx3/vlS6Hyc548SL3kDJzY6Inc7milL0VqmBo9WwdFcutwrnWyAlxTlFBG6a+kEMghbyB1L0ZqpoGwIDAQABAoGBALvjwMohMAduVF7DIPMxvXe6UGdJ2C5Ag8HH1/RlitHxUq58x8dU8FjHJNpZx1UJbAiMNNn/vBiojh+oyEcuOjds0d1LtVS28nk6dkQpaC10bVV/TZRKT3kCoeQfNQ7RgYwp6v6naAwNfJfTPwl1qjCQaqBlAeOrNQoAtN7jAuTBAkEA5VpkTi4lYtCWl4O6ynp0z2ja1xAWqKflp8uXV3MeSkfFmDg+99BfcjbMz7i0RiK3LNG0yl/S9Jax9JlNU2J0qwJBAOKSrYBd2REaCNHPCWBA4ABRWkKSLW9PkXBMoFRvo+tpq3REyxpWs+Yz3oS5ZzrtK7a7tgDgA9fSjdnK1Ia+elECQE5okaQcqJFYqDMSSNiR9r81pKMjj+uGwr+TnaC67V8NnGLGz9get5KvY2OcTJ0xnxfGdZ0+FzuhDSOHCWV5YlMCQA8EmeuATPsNNrhxeLWglzhuLAVtmwVdyM4gxh/SppLcFjlGtg+w34vKtF0nzOfjAJrEJnQ4ZQjRNAXTo/KqfYECQDra6/+GmfkYPivsOe5hGnZ8nCmRgflBpyGRPwoIJXHbxOrW/mCaH8loLhO/TIAkANcQsNeT72TIddhrmx6Izpg=';

        returnApiSuccess('ok',$json_param);
    }

    /**
     * 支付寶回調通知
     */
    public function alinotify(){
        Vendor('alipay/alipayapi');
        $AlipayNotify = new \AlipayNotify();
        //$_POST['notify_id'] = '21610b8819bbc87454e113a61cc76f5kv2';
        if(empty($_POST)){
            logResult('支付宝充值回调数据为空');
            // returnApiError(1,'支付宝回调数据为空');
            return false;
        }

        $success = false;
        $result = $AlipayNotify->verifyNotify($_POST);
        if(($_POST['trade_status'] == 'TRADE_SUCCESS')  || ($_POST['trade_status'] == 'TRADE_FINISHED')){
            $success = true;
        }

        if($result && $success){
             logResult(json_encode($_POST));
            //处理订单数据

            $member = M('member');
            $recharge = M('pd_recharge');

            /*echo '<pre />';
            print_r($result);die;*/
            $pay_sn = $_POST['out_trade_no'];
            // logResult( 'pay_sn='.$pay_sn);
            $recharge_data = $recharge->where("pdr_trade_sn = '$pay_sn'")->find();

            if(!$recharge_data){
                return false;
            }
            if($recharge_data['pdr_payment_state'] == 1){
                echo  "SUCCESS";die;
            }


            $order_arr = array(
                'pdr_payment_time' => time(),
                'pdr_payment_state' => '1',
                'payment_code' => 'wxpay',
                'pdr_payment_name' => '支付宝',
                'pdr_payment_code' => 'wxpay',
            );


            $where['pdr_trade_sn'] = $pay_sn;
            $recharge->where($where)->save($order_arr);

            $uid = $recharge_data['pdr_member_id'];


            // logResult( 'member_id='.$uid);
            $member_data = $member->find($uid);

            $total_fee = $_POST['total_fee'];
            $money = $member_data['available_predeposit'] + $total_fee;


            $save = array(
                'available_predeposit' => $money,
            );
            $member->where("member_id = $uid")->save($save);


        }else{

            return false;
        }
    }

    /**
     * 微信回调通知
     */
    public function wxnotify(){
        Vendor('Wxpay.api');
        $api = new \WxPayNotify();
        $result = $api->Handle();
        //$arr_json = '{"appid":"wx6c112f31beb9b8ac","bank_type":"CFT","cash_fee":"1","fee_type":"CNY","is_subscribe":"N","mch_id":"1337920801","nonce_str":"oibohkym1c0l18dfq1eqbpwjmk50gjbj","openid":"oWUqmxIsYbuSBHFDxhqLxAtr9Nfg","out_trade_no":"890518383361262004","result_code":"SUCCESS","return_code":"SUCCESS","sign":"5A52D41780F94DDFC4F8D2C503E3855D","time_end":"20160604183124","total_fee":"1","trade_type":"APP","transaction_id":"4002902001201606046771610248"}';
        //$result = json_decode($arr_json,true);
        // $result = true;
        if($result == false){
             logResult('微信支付充值回调失败');
            return false;
        } else {
             //logResult(json_encode($result));

            $member = M('member');
            $recharge = M('pd_recharge');

            /*echo '<pre />';
            print_r($result);die;*/
            $pay_sn = $result['out_trade_no'];
           // logResult( 'pay_sn='.$pay_sn);
            $recharge_data = $recharge->where("pdr_trade_sn = '$pay_sn'")->find();

            if(!$recharge_data){
                return false;
            }
            if($recharge_data['pdr_payment_state'] == 1){
                echo  "SUCCESS";die;
            }


            $order_arr = array(
                'pdr_payment_time' => time(),
                'pdr_payment_state' => '1',
                'payment_code' => 'wxpay',
                'pdr_payment_name' => '微信',
                'pdr_payment_code' => 'wxpay',
            );


            $where['pdr_trade_sn'] = $pay_sn;
             $recharge->where($where)->save($order_arr);

            $uid = $recharge_data['pdr_member_id'];


           // logResult( 'member_id='.$uid);
            $member_data = $member->find($uid);

            $total_fee = $result['total_fee']/100;
            $money = $member_data['available_predeposit'] + $total_fee;


            $save = array(
                'available_predeposit' => $money,
            );
            $member->where("member_id = $uid")->save($save);
           // echo $save['available_predeposit'];
           // echo $member->getLastSql();


        }
    }

    /**
     * 充值纪录
     */
    public function record(){
        $pno = I('post.pno',1,'intval') ;     //当前页码
        $pgz  = I('post.pgz',10,'intval') ;   //显示条数
        $uid = I('post.uid',0,'intval');
        if(!$uid) returnApiError(1,'uid参数错误');
        $pindex = $pno ;     //当前页码
        $psize  = $pgz ;   //显示条数
        if(!$pindex)  $pindex = 1;
        $pfirst = ($pindex - 1) * $psize;
        $recharge = M('pd_recharge');
        $data = $recharge->where("pdr_member_id = $uid ")->limit($pfirst .','.$psize)->select();
        if($data) returnApiSuccess('ok',$data);
        returnArr('数据为空');
    }

    /**
     * 消费纪录
     */
    public function consumption(){
        $pno = I('post.pno',1,'intval') ;     //当前页码
        $pgz  = I('post.pgz',10,'intval') ;   //显示条数
        $uid = I('post.uid',0,'intval');
        if(!$uid) returnApiError(1,'uid参数错误');
        $pindex = $pno ;     //当前页码
        $psize  = $pgz ;   //显示条数
        if(!$pindex)  $pindex = 1;
        $pfirst = ($pindex - 1) * $psize;
        $order = M('order');
        $where['payment_code'] = 'balance';
        $where['buyer_id'] = $uid;
        $data = $order->field('order_id,order_sn,pay_sn,pd_amount,payment_time,add_time')->where($where)->limit($pfirst .','.$psize)->select();
        if($data) returnApiSuccess('ok',$data);
        returnArr('数据为空');
    }

}

